package com.jxs.android.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public final class StatusHelper {

	public static boolean isGPSEnabled(Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	public static boolean checkIntentAndGPS(Context context) {
		if (checkNetworkAvailable(context))
			return checkGPS(context);
		return false;
	}

	public static boolean checkGPS(Context context) {
		if (!isGPSEnabled(context)) {
			setting(context, "设置GPS", "GPS开关未开启，请开启", "设置", Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			return false;
		}
		return true;
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		} else {
			NetworkInfo[] ni = cm.getAllNetworkInfo();
			if (ni != null) {
				for (int i = 0; i < ni.length; i++) {
					if (ni[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static boolean checkNetworkAvailable(Context context) {
		if (!isNetworkAvailable(context)) {
			setting(context, "设置网络", "网络未开启，请开启网络", "设置", Settings.ACTION_WIRELESS_SETTINGS);
			return false;
		}
		return true;
	}

	private static void setting(final Context context, String title, String message, String yesBtn, final String settingProvider) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setMessage(message).setCancelable(false).setPositiveButton(yesBtn, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				context.startActivity(new Intent(settingProvider));
				dialog.cancel();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				if (context instanceof Activity) {
					if (Settings.ACTION_WIRELESS_SETTINGS.equals(settingProvider)) {
						if (!isNetworkAvailable(context)) {
							((Activity) context).finish();
						}
					} else if (Settings.ACTION_LOCATION_SOURCE_SETTINGS.equals(settingProvider)) {
						if (!isGPSEnabled(context)) {
							((Activity) context).finish();
						}
					}
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
}